<?php

namespace App\GraphQL\Queries\User;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use App\Models\ExportFile;
use Illuminate\Support\Facades\DB;

class Export
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $keywords = $args['input']['keywords'];
        $role = $args['input']['role'];
        $query = User::query();
        // 根据用户id 搜索条件生成 唯一值 保存导出记录
        $recordHash = md5($keywords.$role);
        $export = ExportFile::where('table','users')->where('record_hash',$recordHash)->where('user_id',auth()->user()->id)->first();
        if(!$export){
            $columns = DB::getDoctrineSchemaManager()->listTableDetails('users');
            if($keywords){
                $query->where(function($query) use($keywords) {
                    $query->where('name','LIKE',"%$keywords%")->orWhere('phone','LIKE',"%$keywords%");
                    $query->orWhere('id_card','LIKE',"%$keywords%");
                });
            }
            if($role){
                $query->where('role_code',$role);
            }
            $data = [];
            // 循环插入数据
            $items = collect($query->with('role')->get()->toArray());
            // 获取一组数据生成表头
            // 
            // 获取users备注表头
            
            // 转换为excel 保存在阿里云
        }

        // 
        return $export;
    }
}
